package cn.wolfcode.luowowo.redis.RedisService.impl;

import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.RedisService.IUserInfoRedisService;
import cn.wolfcode.luowowo.redis.util.RedisKeys;
import cn.wolfcode.luowowo.util.Consts;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRdisServiceImpl implements IUserInfoRedisService {
    //使用redis
    @Autowired
    private StringRedisTemplate template;

    //发送验证码
    @Override
    public void sendVerifyCode(String phone, String code) {

        String key = RedisKeys.VERIFY_CODE.json(phone);
        //缓存信息
        template.opsForValue().set(key, code, RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);

    }

    //获取验证码
    @Override
    public String getVerifyCode(String phone) {
        String key = RedisKeys.VERIFY_CODE.json(phone);
        return template.opsForValue().get(key);
    }
    //将登录用户设置到redis中
    @Override
    public String setToken(UserInfo user) {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        String key = RedisKeys.LOGIN_TOKEN.json(token);
        String value = JSON.toJSONString(user);
        template.opsForValue().set(key, value, RedisKeys.LOGIN_TOKEN.getTime(), TimeUnit.SECONDS);
        return token;
    }

    //通过令牌获取用户信息
    @Override
    public UserInfo getUserByToken(String token) {
        if (!StringUtils.hasLength(token)) {
            return null;
        }
        String key = RedisKeys.LOGIN_TOKEN.json(token);

        String userStr = template.opsForValue().get(key);
        if (StringUtils.hasLength(userStr)) {
            template.expire(key, RedisKeys.LOGIN_TOKEN.getTime(), TimeUnit.SECONDS);
            return JSON.parseObject(userStr, UserInfo.class);
        }

        return null;
    }
}
